package com.cloudbroker.bcs.platform.dav.middle.util;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.util.JSONUtil;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.constant.CacheKeys;
import com.cloudbroker.bcs.platform.dav.common.util.SessionHelper;
import com.cloudbroker.bcs.platform.dav.middle.constants.IFSGoldUrl;

public class GoldTokenUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(GoldTokenUtil.class);
    
    private static final int HOUR_TIMEOUT = 2;
    
    public static String getGoldToken() {
        String gold_token;
        gold_token = SessionHelper.getInstance().fetchInfoByKey(CacheKeys.GOLD_TOKEN);       
        if (StringUtils.isBlank(gold_token)) {
            gold_token = refreshGoldToken();
        }
        return gold_token;
    }
    
    public static String refreshGoldToken() {
        String auth_key = ConfigValues.getGoldAnthKey();
        String auth_secret = ConfigValues.getGoldAnthSecret();
        String url = ConfigValues.getGoldIntUrl() + IFSGoldUrl.GOLD_AUTH;
        Map<String, Object> params = new HashMap<>();
        params.put("auth_key", auth_key);
        params.put("secret", auth_secret);
        String result = HttpsUtil.doHttpsPost(url, params);
        if (StringUtils.isBlank(result)) {
            logger.error("获取Gold user_token失败：" + result);
            return null;
        }
        JSONObject json = JSONUtil.toJsonObject(result);
        String user_token = json.getString("user_token");
        Integer expires_in = json.getInteger("expire_time");
        if (StringUtils.isBlank(user_token)) {
            logger.error("获取Gold user_token失败：" + json.toJSONString());
            return null;
        }
        logger.debug("获取Gold user_token成功：" + user_token);
        
        SessionHelper.getInstance().setInfoForSession(CacheKeys.GOLD_TOKEN, user_token,
                getUpdateTimeout(expires_in));
        return user_token;
    }
    
    private static int getUpdateTimeout(Integer expires_in) {
        int expires_day = expires_in / 60 / 60 / 24;
        Calendar now = Calendar.getInstance();
        Calendar update = Calendar.getInstance();
        long time = 0l;
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH);
        int day = now.get(Calendar.DAY_OF_MONTH);
        int hour = now.get(Calendar.HOUR_OF_DAY);
        if (hour < HOUR_TIMEOUT) {
            update.set(year, month, day + expires_day - 1, HOUR_TIMEOUT, 0, 0);
            time = (update.getTimeInMillis() - now.getTimeInMillis()) / 1000;
        } else {
            update.set(year, month, day + expires_day, HOUR_TIMEOUT, 0, 0);
            time = (update.getTimeInMillis() - now.getTimeInMillis()) / 1000;
        }
        return (int) time;
    }
}
